package com.bytedance.social.common;

import com.bytedance.social.event.SendZhiPuChatEvent;
import com.bytedance.social.http.Choices;
import com.bytedance.social.http.ToAi;
import com.bytedance.social.http.User;
import com.bytedance.social.http.ZhiPu;
import com.bytedance.social.mapper.MessageMapper;
import com.bytedance.social.pojo.Message;
import com.bytedance.social.properties.ZhiPuAiProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Data
@Slf4j
public class AIChatThread extends Thread {
    private ZhiPuAiProperties puAiProperties;
    private MessageMapper messageMapper;
    private RestTemplate restTemplate;
    private SendZhiPuChatEvent sendZhiPuChatEvent;

    @Override
    public void run() {
        //事件到达,接收到来自用户发给人工智能的消息
        Message source = (Message) sendZhiPuChatEvent.getSource();
        ToAi toAi = new ToAi();
        User user = new User();
        user.setContent(source.getContent());
        List<User> users = new ArrayList<>();
        users.add(user);
        toAi.setPrompt(users);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.add("Authorization", puAiProperties.getToken());
        HttpEntity<ToAi> toAiHttpEntity = new HttpEntity<>(toAi, httpHeaders);
        ZhiPu zhiPu = restTemplate.postForObject(puAiProperties.getUrl(), toAiHttpEntity, ZhiPu.class);
        log.error("SendZhiPuChatEvent执行啦");
        List<Choices> choices = zhiPu.getData().getChoices();
        log.error("===============");
        Choices choices1 = choices.get(0);
        log.error(choices1.getContent());
        Message message = new Message();
        message.setFrom_user_id(puAiProperties.getAIId());
        message.setTo_user_id(source.getFrom_user_id());
        message.setContent(choices1.getContent());
        message.setCreate_time(System.currentTimeMillis());
        messageMapper.insertUserMessage(message);

//        for (Choices choice : choices) {
//            if (choice.getRole() == "assistant") {
//                log.info("assistant");
//                Message message = new Message();
//                message.setFrom_user_id(puAiProperties.getAIId());
//                message.setTo_user_id(source.getFrom_user_id());
//                String content = choice.getContent();
//                message.setContent(content);
//                message.setCreate_time(System.currentTimeMillis());
//                log.info(content);
//                //写入数据库
//                messageMapper.insertUserMessage(message);
//            }
//        }


    }
}
